process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'devlopment';

process.on('unhandledRejection', err => {
    throw err;
});

require('../config/env');

const
    fs = require('fs'),
    chalk = require('chalk'),
    webpack = require('webpack'),
    WebpackDevServer = require('webpack-dev-server'),
    clearConsole = require('react-dev-utils/clearConsole'),
    checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'),
    {
        choosePort,
        createCompiler,
        prepareProxy,
        prepareUrls
    } = require('react-dev-utils/WebpackDevServerUtils'),
    openBrowser = require('react-dev-utils/openBrowser'),
    paths = require('../config/paths'),
    config = require('../config/webpack.config.dev.js'),
    createDevServerConfig = require('../config/webpackDevServer.config'),
    userYarn = fs.existsSync(paths.yarnLockFile),
    isInteractive = process.stdout.isTTY
;

if(!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
    process.exit(1);
}

const
    DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000,
    HOST = process.env.HOST || '0.0.0.0'
;

choosePort(HOST, DEFAULT_PORT).then(port => {
    if(port === null) {
        return;
    }

    const
        protocol = process.env.HTTPS === 'true' ? 'https' : 'http',
        appName = require(paths.appPackageJson).name,
        urls = prepareUrls(protocol, HOST, port),
        compiler = createCompiler(webpack, config, appName, urls, userYarn),
        proxySetting = require(paths.appPackageJson).proxy,
        proxyConfig = prepareProxy(proxySetting, paths.appPublic),
        serverConfig = createDevServerConfig(proxyConfig, urls.lanUrlForConfig),
        devServer = new WebpackDevServer(compiler, serverConfig)
    ;

    devServer.listen(port, HOST, err => {
        if(err) {
            return console.log(err);
        }

        if(isInteractive) {
            clearConsole();
        }
        console.log(chalk.cyan('Starting the development server...\n'));
        openBrowser(urls.localUrlForBrowser);
    });

    ['SIGINT', 'SIGTERM'].forEach(sig => {
        process.on(sig, () => {
            devServer.close();
            process.exit();
        });
    });
}).catch(err => {
    if(err && err.message) {
        console.log(err.message);
    }

    process.exit(1);
});